#include <sys/mman.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
using namespace std;

int main()
{
    /* 获取文件大小 */
    const char *filename = "./tongxin.txt";
    int fd = open(filename, O_RDWR);
    if (fd == -1)
    {
        perror("open error:");
        exit(-1);
    }

    off_t length = lseek(fd, 0, SEEK_END);

    void *address = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (address == MAP_FAILED)
    {
        perror("mmap error:");
        exit(-1);
    }

    /* 关闭文件描述符  */
    close(fd);

    /* 创建进程 */
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork error:");
        exit(-1);
    }
    else if (pid == 0)
    {
        /*子进程*/
        sleep(1);
        cout << "data:" << (char *)address << endl;

        _exit(0);
    }
    else
    {
        /*父进程*/
        /*写数据*/
        const char *data = "hello world.";
        strcpy(static_cast<char *>(address), data);

        /*回收子进程资源*/
        wait(NULL);
    }

    /*释放共享内存空间*/
    munmap(address, length);

    return 0;
}
